"use strict"
var fs = require('fs');
var Weibo = require('./Weibo');
class WeiboManager {
    constructor() {
        this.databaseFile = 'database.json';
        this.weibos = {};
        if (fs.existsSync(this.databaseFile)) {
            fs.readFile(this.databaseFile, (err, data) => {
                if (err) throw err;
                var tokenArrs = JSON.parse(data);
                console.log(`init ${tokenArrs.length} weibos!`);
                tokenArrs.forEach((token) => {
                    if (!token.uid) {
                        return;
                    }
                    if (token.expire_at < (new Date).getTime()) {
                        return;
                    }
                    this.weibos[token.uid] = new Weibo(token);
                })
                if (this.getWeibos().length != tokenArrs.length) {
                    this._syncToFile();
                }
            });
        }
    }
    _syncToFile() {
        var tokenObjs = [];
        for (var uid in this.weibos) {
            var weibo = this.weibos[uid];
            tokenObjs.push(weibo.getToken());
        }
        fs.writeFile("database.json", JSON.stringify(tokenObjs), function(err) {
            if (err) throw err;
            console.log(`saved ${tokenObjs.length} weibos!`)
        });
    }
    save(weibo) {
        this.weibos[weibo.getUid()] = weibo;
        this._syncToFile();
    }
    getWeiboById(uid) {
        return this.weibos[uid];
    }
    getWeibos() {
        var arr = [];
        for (var uid in this.weibos) {
            arr.push(this.weibos[uid]);
        }
        return arr;
    }
    removeWeibo(uid) {
        if (this.weibos['uid']) {
            delete this.weibos['uid'];
            this._syncToFile();
        }
    }
}
exports = module.exports = new WeiboManager
